<template>
  <div class="alloc-resource">
    <el-card>
      <template #header>
        <span>分配资源</span>
      </template>
      <el-tree
        ref="tree"
        :data="resources"
        node-key="id"
        :props="{
          children: 'children',
          label: 'name'
        }"
        show-checkbox
        :default-checked-keys="defaultCheckedKeys"
        :default-expanded-keys="defaultCheckedKeys"
      />
      <div style="text-align: center">
        <el-button @click="resetChecked">
          清空
        </el-button>
        <el-button
          type="primary"
          @click="onSave"
        >
          保存
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { ElMessage } from 'element-plus'
import { DefineComponent, defineComponent, onBeforeMount, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  getAllResources,
  allocateRoleResources,
  getRoleResources
} from '/@/services/resource'
import { getResourceCategories } from '/@/services/resource-category'

const tree = ref<DefineComponent | null>(null)
// 页面进入初始化
const useInitResources = (roleId: number) => {
  const resources = ref([])
  const defaultCheckedKeys = ref([])
  const loadResources = async () => {
    const ret = await Promise.all([getAllResources(), getResourceCategories()])
    const resourcesTmp = ret[0].data.data
    const resourceCategories = ret[1].data.data

    resourcesTmp.forEach((r: any) => {
      const category = resourceCategories.find((c: any) => c.id === r.categoryId)
      if (category) {
        category.children = category.children || []
        category.children.push(r)
      }
    })
    // 修改顶层分类 ID：因为分类 ID 和资源 ID 冲突
    resourceCategories.forEach((item: any) => {
      item.id = Math.random()
    })

    resources.value = resourceCategories
  }

  const loadRoleResources = async () => {
    const { data } = await getRoleResources(roleId)
    getCheckedResources(data.data)
  }

  const getCheckedResources = (roleResources: any) => {
    roleResources.forEach((r: any) => {
      r.resourceList && r.resourceList.forEach((c: any) => {
        if (c.selected) {
          defaultCheckedKeys.value = [...defaultCheckedKeys.value, c.id] as any
        }
      })
    })
  }

  onBeforeMount(() => {
    loadResources()
    loadRoleResources()
  })

  return {
    resources,
    defaultCheckedKeys
  }
}
// 操作集合
const useHandles = (roleId: number) => {
  const router = useRouter()
  const onSave = async () => {
    const checkedNodes: [] = (tree.value as DefineComponent).getCheckedNodes()
    const resourceIdList: number[] = []
    checkedNodes.forEach((item: any) => {
      if (!item.children) {
        resourceIdList.push(item.id)
      }
    })
    await allocateRoleResources({
      roleId: roleId,
      resourceIdList
    })
    ElMessage.success('保存成功')
    router.back()
  }

  const resetChecked = () => {
    (tree.value as DefineComponent).setCheckedKeys([])
  }
  return {
    onSave,
    resetChecked
  }
}
export default defineComponent({
  name: 'AllocResource',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  setup (props) {
    return {
      tree,
      ...useInitResources(+props.roleId),
      ...useHandles(+props.roleId)
    }
  },
  methods: {

  }
})
</script>

<style lang="scss" scoped></style>
